package com.qut.graduate.busrtquery.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.busline.BusLineResult;
import com.baidu.mapapi.search.busline.BusLineSearch;
import com.baidu.mapapi.search.busline.BusLineSearchOption;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.qut.graduate.busrtquery.BRTQCache;
import com.qut.graduate.busrtquery.BRTQConstant;
import com.qut.graduate.busrtquery.BaseActivity;
import com.qut.graduate.busrtquery.R;
import com.qut.graduate.busrtquery.adapter.BusRealTimeInfoAdapter;
import com.qut.graduate.busrtquery.adapter.BusRealTimeStationAdapter;
import com.qut.graduate.busrtquery.bean.BusLineInfo;
import com.qut.graduate.busrtquery.bean.BusRealTimeInfo;
import com.qut.graduate.busrtquery.bean.BusStation;
import com.qut.graduate.busrtquery.bean.Route;
import com.qut.graduate.busrtquery.bean.User;
import com.qut.graduate.busrtquery.greendao.bean.BusLineCollect;
import com.qut.graduate.busrtquery.greendao.controller.DBController;
import com.qut.graduate.busrtquery.interfaces.OnItemClickListener;
import com.qut.graduate.busrtquery.utils.baidumap.BaiduMapUtils;
import com.qut.graduate.busrtquery.utils.baidumap.BusLineOverlay;
import com.qut.graduate.busrtquery.utils.common.FormatUtils;
import com.qut.graduate.busrtquery.utils.common.GsonUtils;
import com.qut.graduate.busrtquery.utils.common.LogUtils;
import com.qut.graduate.busrtquery.utils.net.HttpUtil;
import com.qut.graduate.busrtquery.utils.uiabout.ScreenUtils;
import com.qut.graduate.busrtquery.utils.uiabout.StatusBarUtils;
import com.qut.graduate.busrtquery.utils.uiabout.ToastColorfulUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.BmobUser;

/**
 * @Author WLL
 * @Time: 2019/4/27 19:24
 */
public class BusRouteRealTimeInfoActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "BusRouteRealTimeInfoAct";
    private Context context;
    private Timer timer;
    private MapView mMapView = null;
    private BaiduMap mBaiduMap;
    private BusLineResult route = null; // 保存驾车/步行路线数据的变量，供浏览节点时使用
    private List<String> busLineIDList = null;
    private int busLineIndex = 0;
    private BusLineOverlay overlay; // 公交路线绘制对象
    private PoiSearch mSearch = null; // 搜索模块，也可去掉地图模块独立使用
    private BusLineSearch mBusLineSearch = null;  // 搜索公交线路
    private String city;
    private String busName;
    private boolean isCollect = false; // 判断是否收藏，true为收藏，false为未收藏
    private Route busRoute;
    private boolean isFirstRequest = true; // 是否是第一次请求“站点的公交车实时情况”
    private int urlListSize = 0; // http请求达到30次清空list
    private List<String> urlList; // 存放所有请求“站点的公交车实时情况”的http地址
    private BusLineInfo busLineInfo; // 当前公交线路的总体信息，起终点站、起终时间、价格等信息
    private List<BusStation> busStationList; // 当前公交线路的所有站点信息包括上行、逆行
    private List<BusRealTimeInfo> busRealTimeInfoTotalList; // urlList中请求后返回的所有公交车车辆实时信息存放到这里
    private List<BusRealTimeInfo> busRealTimeInfoTotalListCopy;
    private int direct = BRTQConstant.BUS_DIRECT_UP; // 公交线路方向，1为上行，0为下行
    private BusRealTimeStationAdapter busRealTimeStationAdapter;
    private BusRealTimeInfoAdapter busRealTimeInfoAdapter;
    private TextView mBusName;
    private Button mCollectBtn;
    private ImageButton mCollectBtn2;
    private TextView mStartEndStation;
    private TextView mPriceInfo;
    private TextView mStartStationTime;
    private TextView mEndStationTime;
    private RecyclerView mRealTimeInfoRecyclerView;
    private RecyclerView mRealTimeStationRecyclerView;
    private TextView mNowBusStation;
    private TextView mNextBusTitle;
    private TextView mNextBusPlate;
    private TextView mNextBusStationNum;
    private TextView mNextBusDistance;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bus_route_real_time_info;
    }

    @Override
    protected void init() {
        this.context = this;
        StatusBarUtils.setStatusBarTransparent(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        mSearch = PoiSearch.newInstance();
        mSearch.setOnGetPoiSearchResultListener(this);
        mBusLineSearch = BusLineSearch.newInstance();
        mBusLineSearch.setOnGetBusLineSearchResultListener(this);
        busLineIDList = new ArrayList<String>();
        overlay = new BusLineOverlay(mBaiduMap);
        urlList = new ArrayList<>();
        busRealTimeInfoTotalList = new ArrayList<>();
        busRealTimeInfoTotalListCopy = new ArrayList<>();

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            city = bundle.getString("city");
            busRoute = bundle.getParcelable("route");
            busName = busRoute.getRoutename();
            busLineInfo = bundle.getParcelable("busLineInfo");
            busStationList = bundle.getParcelableArrayList("busStationList");
            for (int i = 0; i < busStationList.size(); i++) {
                String url = BRTQConstant.URL_BUS_REAL_TIME_INFO.concat(busRoute.getRouteid()).concat("&smid=")
                        .concat(busRoute.getSegment()).concat("&id=").concat(String.valueOf(i + 1)).concat("&from=m");
                urlList.add(url);
            }
//            LogUtils.d("----实时公交信息界面----busLineInfo: " + busLineInfo, getClass());
//            for (int i = 0; i < busStationList.size(); i++) {
//                LogUtils.d("----实时公交信息界面----busStationList: " + busStationList.get(i), getClass());
//            }
//            LogUtils.d("----实时公交信息界面----urlList: " + urlList, getClass());
        } else {
            city = "青岛";
            busName = "1路";
        }
        searchBusLine();
        setBusInfo();
        setBusRealTimeStationRecyclerView();
        for (String url : urlList) {
            HttpUtil.getInstance().getAsyn(url, this, BRTQConstant.HTTP_TAG_BUS_REAL_TIME_INFO);
        }
        timer = new Timer();
        if (task != null) {
            timer.schedule(task, 0, 20000);
        }

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (overlay.getmOverlayList() != null && overlay.getmOverlayList().contains(marker)) {
                    int index = overlay.getmOverlayList().indexOf(marker);
                    if (route.getStations() != null && route.getStations().get(index) != null) {
                        nodeClick(index);
                    }
                }
                return true;
            }
        });
    }

    // 设置公交线路起终时间、价格等基本的一些信息
    private void setBusInfo() {
        mStartEndStation.setText(busLineInfo.getLine1());
        mPriceInfo.setText(busLineInfo.getPrice());
        mStartStationTime.setText(busLineInfo.getTime());
        mEndStationTime.setText(busLineInfo.getTime1());
        setNoCarInfo(0);

        User user = BmobUser.getCurrentUser(User.class);
        if (user != null) {
            List<BusLineCollect> busLineCollects = BRTQCache.getInstance().getBusLineCollectList();
            for (int i = 0; i < busLineCollects.size(); i++) {
                if (busName.equals(busLineCollects.get(i).getName())){
                    isCollect = true;
                    break;
                }
                else isCollect = false;
            }
            setWhichCollectBtnVisibility(isCollect);
        } else
            setWhichCollectBtnVisibility(false);
    }

    // 设置当前线路上行所有站点的recyclerview的适配器等
    public void setBusRealTimeStationRecyclerView() {
        mRealTimeStationRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        busRealTimeStationAdapter = new BusRealTimeStationAdapter(this, busStationList);
        mRealTimeStationRecyclerView.setAdapter(busRealTimeStationAdapter);
        busRealTimeStationAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                nodeClick(position);
                int upRouteSize = BRTQCache.getInstance().getUpRouteSize();
                if (direct == BRTQConstant.BUS_DIRECT_UP) {
                    HttpUtil.getInstance().getAsyn(urlList.get(position), BusRouteRealTimeInfoActivity.this, BRTQConstant.HTTP_TAG_BUS_REAL_TIME_INFO_ONLY);
                    mNowBusStation.setText("（上）".concat(busStationList.get(position).getStaionname()));
                } else {
                    HttpUtil.getInstance().getAsyn(urlList.get(upRouteSize + position), BusRouteRealTimeInfoActivity.this, BRTQConstant.HTTP_TAG_BUS_REAL_TIME_INFO_ONLY);
                    mNowBusStation.setText("（下）".concat(busStationList.get(upRouteSize + position).getStaionname()));
                }
            }
        });
    }

    @Override
    public void onHttpSuccess(String json, int tag) {
        String responseJson = FormatUtils.unicodeToString(json);
        if (tag == BRTQConstant.HTTP_TAG_BUS_REAL_TIME_INFO) {
            try {
                requestBusRealTimeInfo(responseJson);
            } catch (Exception e) {
                LogUtils.d("----实时公交信息界面  HTTP_TAG_BUS_REAL_TIME_INFO http请求异常: " + e, getClass());
            }
        }
        if (tag == BRTQConstant.HTTP_TAG_BUS_REAL_TIME_INFO_ONLY) {
            requestBusRealTimeInfoOnly(responseJson);
        }
    }

    @Override
    public void onHttpFailed(String errorMsg, int tag) {
        LogUtils.d("----实时公交信息界面 HttpFailed  errorMsg  " + errorMsg);
    }

    // 设置没获取到具体站点车辆实时信息时设置的文本提示信息, tag 0 表示显示"点击站点查询"，1 表示显示"暂无车辆"
    public void setNoCarInfo(int tag) {
        if (tag == 0) mNowBusStation.setText("点击站点查询");
        mNextBusTitle.setText("暂无车辆");
        mNextBusPlate.setText("车牌：--");
        mNextBusStationNum.setText("--  站");
        mNextBusDistance.setText("--  ".concat("km"));
    }

    // 请求某一个点击站点的公交车车辆实时信息
    public void requestBusRealTimeInfoOnly(String responseJson) {
        List<BusRealTimeInfo> busRealTimeInfoOnlyList = new ArrayList<>();
        if (responseJson.contains("car_num")) {
            busRealTimeInfoOnlyList = GsonUtils.getInstance().jsonToList(responseJson, BusRealTimeInfo.class);
//            LogUtils.d("----实时公交信息界面  HTTP_TAG_BUS_REAL_TIME_INFO_ONLY busRealTimeInfoOnlyList: " + busRealTimeInfoOnlyList, getClass());
            final List<BusRealTimeInfo> finalBusRealTimeInfoOnlyList = busRealTimeInfoOnlyList;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (finalBusRealTimeInfoOnlyList != null && finalBusRealTimeInfoOnlyList.size() > 0) {
                        mNextBusTitle.setText("下一辆");
                        mNextBusPlate.setText("车牌：".concat(finalBusRealTimeInfoOnlyList.get(0).getCar_num()));
                        mNextBusStationNum.setText(finalBusRealTimeInfoOnlyList.get(0).getStation_count_remain().concat("站"));
                    } else {
                        setNoCarInfo(1);
                    }
                }
            });
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setNoCarInfo(1);
                }
            });
        }
    }

    // 请求所有站点的公交车车辆实时信息
    public void requestBusRealTimeInfo(String responseJson) {
        if (responseJson.contains("car_num")) {
            List<BusRealTimeInfo> busRealTimeInfoList = GsonUtils.getInstance().jsonToList(responseJson, BusRealTimeInfo.class);
            busRealTimeInfoTotalList.addAll(busRealTimeInfoList);
        }
        urlListSize += 1;
        if (urlListSize == urlList.size()) {
            urlListSize = 0;
            if (busRealTimeInfoTotalList != null)
                deleteRepeatBusRealTimeInfo(busRealTimeInfoTotalList);
            busRealTimeInfoTotalListCopy.addAll(busRealTimeInfoTotalList);
//            LogUtils.d("----实时公交信息界面 HttpSuccess  复制list busRealTimeInfoTotalListCopy:" + busRealTimeInfoTotalListCopy, getClass());
            if (isFirstRequest) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setBusRealTimeInfoRecyclerView();
                        isFirstRequest = false;
                        busRealTimeInfoTotalListCopy.clear();
                    }
                });
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (busRealTimeInfoAdapter != null && busRealTimeInfoTotalListCopy != null && busRealTimeInfoTotalListCopy.size() > 0)
                            busRealTimeInfoAdapter.updateData(busRealTimeInfoTotalListCopy);
                        else
                            setBusRealTimeInfoRecyclerView();
                        busRealTimeInfoTotalListCopy.clear();
                    }
                });
            }
            busRealTimeInfoTotalList.clear();
        }
    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            LogUtils.d("----实时公交信息界面  TimerTask执行了", getClass());
            for (String url : urlList) {
                HttpUtil.getInstance().getAsyn(url, BusRouteRealTimeInfoActivity.this, BRTQConstant.HTTP_TAG_BUS_REAL_TIME_INFO);
            }
        }
    };

    // 设置当前线路上行站点的公交车车辆实时信息的recyclerview的适配器等
    public void setBusRealTimeInfoRecyclerView() {
        if (busRealTimeInfoTotalListCopy != null && busRealTimeInfoTotalListCopy.size() > 0) {
            mRealTimeInfoRecyclerView.setLayoutManager(new LinearLayoutManager(context));
            busRealTimeInfoAdapter = new BusRealTimeInfoAdapter(this, busStationList, busRealTimeInfoTotalListCopy);
            mRealTimeInfoRecyclerView.setAdapter(busRealTimeInfoAdapter);
        }
    }

    /**
     * 删除重复的公交车牌及到达时间等信息
     *
     * @param busRealTimeInfoTotalList
     */
    public void deleteRepeatBusRealTimeInfo(List<BusRealTimeInfo> busRealTimeInfoTotalList) {
        if (busRealTimeInfoTotalList != null && busRealTimeInfoTotalList.size() > 0) {
            for (int i = 0; i < busRealTimeInfoTotalList.size(); i++) {
                for (int j = 0; j < i; j++) {
                    if (busRealTimeInfoTotalList.get(i) != null && busRealTimeInfoTotalList.get(j) != null)
                        if (busRealTimeInfoTotalList.get(i).getCar_num().equals(busRealTimeInfoTotalList.get(j).getCar_num())) {
                            busRealTimeInfoTotalList.remove(i);
                            i = i - 1;
                            break;
                        }
                }
            }
        }
    }

    // 点击站点后显示该站点所在位置
    public void nodeClick(int position) {
        if (position < overlay.getmOverlayList().size()){
            BaiduMapUtils.startScaleAnimation((Marker) overlay.getmOverlayList().get(position));
            TextView popupText = new TextView(this);
            popupText.setBackgroundResource(R.mipmap.popup);
            popupText.setTextColor(0xff000000);
            try {
                if (route != null) {
                    // 移动到指定索引的坐标
                    mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(route.getStations().get(position).getLocation()));
                    popupText.setText(route.getStations().get(position).getTitle()); // 弹出泡泡
                    mBaiduMap.showInfoWindow(new InfoWindow(popupText, route.getStations().get(position).getLocation(), 10));
                }
            } catch (Exception e) {
                LogUtils.d("----实时公交信息界面  nodeClick异常：" + e, getClass());
            }
        }
    }

    // 发起poi检索
    public void searchBusLine() {
        busLineIDList.clear();
        busLineIndex = 0;
        // 发起poi检索，从得到所有poi中找到公交线路类型的poi，再使用该poi的uid进行公交详情搜索
        mSearch.searchInCity((new PoiCitySearchOption()).city(city).keyword(busName));
        mBusName.setText(busName);
    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            LogUtils.d("----实时公交信息界面 onGetPoiResult： 抱歉，未找到结果");
            return;
        }
        busLineIDList.clear(); // 遍历所有poi，找到类型为公交线路的poi
        for (PoiInfo poi : result.getAllPoi()) {
            busLineIDList.add(poi.uid);
        }
        searchChangeDirectionBusLine();
        route = null;
    }

    // 检索切换方向后的公交线路
    public void searchChangeDirectionBusLine() {
        if (busLineIndex >= busLineIDList.size()) {
            busLineIndex = 0;
        }
        if (busLineIndex >= 0 && busLineIndex < busLineIDList.size() && busLineIDList.size() > 0) {
            if (direct == BRTQConstant.BUS_DIRECT_UP)
                mBusLineSearch.searchBusLine((new BusLineSearchOption().city(city).uid(busLineIDList.get(0))));
            else
                mBusLineSearch.searchBusLine((new BusLineSearchOption().city(city).uid(busLineIDList.get(1))));
        }
    }

    @Override
    public void onGetBusLineResult(BusLineResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            LogUtils.d("----实时公交信息界面 onGetBusLineResult： 抱歉，未找到结果");
            return;
        }
        mBaiduMap.clear();
        route = result;
        overlay.removeFromMap();
        overlay.setData(result);
        overlay.addToMap();
        overlay.zoomToSpan();
        LogUtils.d("----实时公交信息界面 onGetBusLineResult result.getBusLineName：" + result.getBusLineName());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bus_route_real_time_info_back_imgBtn:
                finish();
                break;
            case R.id.bus_route_real_time_info_changeDirectionImage:
                if (direct == BRTQConstant.BUS_DIRECT_UP) {
                    mStartEndStation.setText(busLineInfo.getLine2());
                    direct = BRTQConstant.BUS_DIRECT_DOWN;
                } else {
                    mStartEndStation.setText(busLineInfo.getLine1());
                    direct = BRTQConstant.BUS_DIRECT_UP;
                }
                if (busRealTimeInfoAdapter != null)
                    busRealTimeInfoAdapter.setmDirect(direct);
                if (busRealTimeStationAdapter != null)
                    busRealTimeStationAdapter.setmDirect(direct);
                searchChangeDirectionBusLine();
                break;
            case R.id.bus_route_real_time_info_collectBtn:
                User user = BmobUser.getCurrentUser(User.class);
                if (user != null) {
                    if (isCollect) { // 已经收藏了从内存和数据库中删除
                        deleteBusLineCollect();
                        return; // 如果这里不return，会继续执行下面的代码
                    } else {
                        isCollect = true;
                        setWhichCollectBtnVisibility(isCollect);
                        if (busRoute!=null){
                            BusLineCollect busLineCollect = new BusLineCollect(busRoute);
                            BRTQCache.getInstance().getBusLineCollectList().add(busLineCollect);
                            deleteRepeatBusLineCollect(BRTQCache.getInstance().getBusLineCollectList());
                            DBController.getInstance().insertTable(BRTQConstant.DB_TABLE_TYPE_BUS_LINE_COLLECT,busLineCollect);
                            LogUtils.d("----实时公交信息界面 数据库插入收藏表该收藏线路 " + busLineCollect);
                        }
                    }
                } else
                    ToastColorfulUtils.error("登录后才能收藏公交线路");
                break;
            case R.id.bus_route_real_time_info_collectBtn2:
                deleteBusLineCollect();
                break;
        }
    }

    public void deleteBusLineCollect(){
        isCollect = false;
        setWhichCollectBtnVisibility(isCollect);
        List<BusLineCollect> busLineCollects = BRTQCache.getInstance().getBusLineCollectList();
        LogUtils.d("----实时公交信息界面 所有收藏线路 busLineCollects： " + busLineCollects);
        for (int i = 0; i < busLineCollects.size(); i++) {
            if (busLineCollects.get(i).getName().equals(busName)){
                LogUtils.d("----实时公交信息界面 数据库删除收藏表该收藏线路：" + busLineCollects.get(i));
                busLineCollects.remove(i);
            }
        }
        List<BusLineCollect> busLineCollectList = (ArrayList<BusLineCollect>) DBController.getInstance().
                queryObjectByName(BRTQConstant.DB_TABLE_TYPE_BUS_LINE_COLLECT, busName);
        DBController.getInstance().deleteTable(BRTQConstant.DB_TABLE_TYPE_BUS_LINE_COLLECT,
                busLineCollectList.get(0));
    }

    public void deleteRepeatBusLineCollect(List<BusLineCollect> busLines) {
        for (int i = 0; i < busLines.size(); i++) {
            for (int j = 0; j < i; j++) {
                if (busLines.get(i).getName().equals(busLines.get(j).getName())) {
                    busLines.remove(i);
                    i = i - 1;
                    break;
                }
            }
        }
    }

    /**
     * 只是设置显示还是不显示收藏的按钮
     *
     * @param collect
     */
    public void setWhichCollectBtnVisibility(boolean collect) {
        if (collect) {
            mCollectBtn.setVisibility(View.GONE);
            mCollectBtn2.setVisibility(View.VISIBLE);
        } else {
            mCollectBtn.setVisibility(View.VISIBLE);
            mCollectBtn2.setVisibility(View.GONE);
        }
    }

    public void initView() {
        mMapView = findViewById(R.id.bus_route_real_time_info_mapView);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setViewPadding(ScreenUtils.dp2px(10), 0, 0, 0);
        BaiduMapUtils.changeDefaultBaiDuMapView(mMapView, mBaiduMap); // 比列尺、放大、缩小按钮、图标等的显示与否
        ImageButton mBackBtn = findViewById(R.id.bus_route_real_time_info_back_imgBtn);
        mBusName = findViewById(R.id.bus_route_real_time_info_busName);
        mCollectBtn = findViewById(R.id.bus_route_real_time_info_collectBtn);
        mCollectBtn2 = findViewById(R.id.bus_route_real_time_info_collectBtn2);
        mStartEndStation = findViewById(R.id.bus_route_real_time_info_startEndStation);
        mPriceInfo = findViewById(R.id.bus_route_real_time_info_priceInfo);
        mStartStationTime = findViewById(R.id.bus_route_real_time_info_startStationTime);
        mEndStationTime = findViewById(R.id.bus_route_real_time_info_endStationTime);
        ImageView mChangeDirectionImage = findViewById(R.id.bus_route_real_time_info_changeDirectionImage);
        mRealTimeInfoRecyclerView = findViewById(R.id.bus_route_real_time_info_recyclerView);
        mRealTimeStationRecyclerView = findViewById(R.id.bus_route_real_time_station_recyclerView);
        mNowBusStation = findViewById(R.id.bus_route_real_time_info_nowStation);
        mNextBusTitle = findViewById(R.id.bus_route_real_time_info_nextBusTitle);
        mNextBusPlate = findViewById(R.id.bus_route_real_time_info_nextBusPlate);
        mNextBusStationNum = findViewById(R.id.bus_route_real_time_info_nextBusStationNum);
        mNextBusDistance = findViewById(R.id.bus_route_real_time_info_nextBusDistance);

        mBackBtn.setOnClickListener(this);
        mChangeDirectionImage.setOnClickListener(this);
        mCollectBtn.setOnClickListener(this);
        mCollectBtn2.setOnClickListener(this);

        mRealTimeInfoRecyclerView.addOnScrollListener(new MyScrollListener(mRealTimeStationRecyclerView));
        mRealTimeStationRecyclerView.addOnScrollListener(new MyScrollListener(mRealTimeInfoRecyclerView));

        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                overlay.zoomToSpan();
                mBaiduMap.hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mSearch.destroy();
        mBusLineSearch.destroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel(); // 将原任务从队列中移除
        }
    }

    // 让当前界面的两个recyclerview一起滑动
    private class MyScrollListener extends RecyclerView.OnScrollListener {
        private RecyclerView mRecyclerView;

        public MyScrollListener(RecyclerView recyclerView) {
            this.mRecyclerView = recyclerView;
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (RecyclerView.SCROLL_STATE_IDLE != recyclerView.getScrollState()) {
                mRecyclerView.scrollBy(dx, dy);
            }
        }
    }

}